import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Demo16 {
    private DatagramSocket socket = null;
    public Demo16(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器上线！");
        while(true){
            DatagramPacket requesPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requesPacket);
            String request = new String(requesPacket.getData(),0,requesPacket.getLength());
            String response = process(request);
            //因为有 客户端发送的 requestPacket 所以不需要把 IP 和 端口 拆开来写
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requesPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s,%d],req=%s,resp=%s\n",requesPacket.getAddress(),requesPacket.getPort(),
                    request,response);
        }
    }

    private String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        Demo16 demo16 = new Demo16(9090);
        demo16.start();
    }
}
// byte数组 转成 字符串 getData.
// 字符串 转成 byte数组 通过 getBytes()